package com.lty.mq.project;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

@Component
@Slf4j
public class RabbitMQProducer {

    @Value("${spring.rabbitmq.host}")
    private String host;

    @Value("${rabbitmq.username:guest}")
    private String username;

    @Value("${rabbitmq.password:guest}")
    private String password;

    @Value("${rabbitmq.queue.name:hello}")
    private String queueName;

    @PostConstruct
    public void init() {
        new Thread(this::sendMessage).start();
    }

    private void sendMessage() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setUsername(username);
        factory.setPassword(password);

        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            // 声明队列（确保队列存在）
            channel.queueDeclare(queueName, false, false, false, null);

            String message = "Hello from RabbitMQ Producer!";
            channel.basicPublish("", queueName, null, message.getBytes("UTF-8"));
            log.info("Sent Message: '{}'", message);

        } catch (IOException | TimeoutException e) {
            log.error("Failed to send message via RabbitMQ", e);
        }
    }

    /**
     * 发送自定义消息到 RabbitMQ 队列
     *
     * @param message 要发送的消息内容
     */
    public void sendCustomMessage(String message) {
        new Thread(() -> {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(host);
            factory.setUsername(username);
            factory.setPassword(password);

            try {
                Connection connection = factory.newConnection();
                Channel channel = connection.createChannel();

                // 声明队列（确保队列存在）
                channel.queueDeclare(queueName, false, false, false, null);

                channel.basicPublish("", queueName, null, message.getBytes("UTF-8"));
                log.info("Sent Custom Message: '{}'", message);

            } catch (IOException | TimeoutException e) {
                log.error("Failed to send custom message via RabbitMQ", e);
            }
        }).start();
    }
}
